package by.amakarevich.webapp.page.booking.info;

import java.util.List;

import javax.inject.Inject;

import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.ResourceModel;

import by.amakarevich.datamodel.Booking;
import by.amakarevich.datamodel.BookingInfo;
import by.amakarevich.services.BookingInfoService;
import by.amakarevich.services.BookingService;
import by.amakarevich.webapp.page.AlternativeBaseLayout;
import by.amakarevich.webapp.page.address.DeliveryAddressPage;
import by.amakarevich.webapp.page.booking.info.panel.BookingInfoPanel;

public class BookingInfoPage extends AlternativeBaseLayout {
	
	@Inject
	private BookingInfoService bookingInfoService;
	
	@Inject
	private BookingService bookingService;
	
	private Booking booking;
	private Long totalPrice;
	
	public BookingInfoPage(Booking booking){
		this.booking=booking;
	}
	
	@Override
	protected void onInitialize() {
		super.onInitialize();
		
		final List<BookingInfo> allBookingInfo = bookingInfoService.getAllByBooking(booking);
		
		PriceValidation(allBookingInfo);
		
		add(new ListView<BookingInfo>("details-panel",allBookingInfo) {
			@Override
			protected void populateItem(ListItem<BookingInfo> item) {
				BookingInfo bookingInfo = item.getModelObject();
				item.add(new Label("id", bookingInfo.getId()).setVisible(false));
				item.add((new BookingInfoPanel("booking-info-panel", bookingInfo,booking)));
				
			}
		});
		
		add(new Label("totalPrice", new Model<Long>(booking.getTotalPrice())));
		
		add(new Link("delivery-address-page-link") {
			@Override
			public void onClick() {
				setResponsePage(new DeliveryAddressPage(booking));
			}
		});

	}
	
	private Long PriceValidation(List<BookingInfo> allBookingInfo){
		totalPrice=0l;
		for (BookingInfo bookingInfoPrice : allBookingInfo) {
			totalPrice= totalPrice + bookingInfoPrice.getPrice()*bookingInfoPrice.getQuantity();
		}
		
		if(booking.getTotalPrice()!=totalPrice){
			booking.setTotalPrice(totalPrice);
			bookingService.updateBooking(booking);
		}
		return totalPrice;
	}
	
	@Override
	protected IModel<String> getPageTitle() {
		return new ResourceModel("p.booking.info.title");
	}	
}
